-- @Author: anchen
-- @Date:   2019-11-28 18:34:36
-- @Last Modified by:   anchen
-- @Last Modified time: 2019-12-11 13:54:41
-- @Description: 红包扫雷入口

local game_name = "hbsl" --目录名
local skynet = require("skynet")

local Hotfix = require("Hotfix")
local MessageDispatch = import("MessageDispatch") --使用import 的才可以热更
local UserManager = import("UserManager")
local DeskMessage = import("DeskMessage")
local RoomConfig = import("RoomConfig")
local RobotManager = import("RobotManager")
local StoreManager = import("StoreManager")

local MessageHandler = import(game_name..".MessageHandler")
local Desk = import(game_name..".Desk")

--此服务唯一全局变量, 
global = {}

--禁止出现别的全局变量
local function disable_global()
    local __g = _G
    setmetatable(global, {
        __newindex = function(_, name, value)
            rawset(__g, name, value)
        end,
        __index = function(_, name)
            return rawget(__g, name)
        end
    })
    --防止手误写出全局变量
    setmetatable(__g, {
        __newindex = function(_, name, value)
            local msg = "USE 'global.%s = value' INSTEAD OF SET GLOBAL VARIABLE"
            error(string.format(msg, name), 0)
        end,
    })
end

-- local function resetFu(robotmgr)
--     local C = getmetatable(robotmgr).__index
--     C.loadRobot = function(self,...)
--         local room_data = self.room_data
--         if not room_data  then
--             errlog('load_robot fail because room_data is nil or not open_robot')
--             return
--         end
--         if not room_data.open_robot then --关闭了机器人
--         -- if true then 
--             for uid, robot in pairs(self.robot_list) do
--                 if not robot:isClose() then 
--                     robot:leaveReq()
--                 end
--             end
--             dbglog("______room_data____close__robot_____________")
--             return 
--         end
--         local robot_type = room_data.robot_type  --baijiale_normal
--         -- ["count_range"] = "5,10", 人数范围
--         -- ["coins_range"] = "1000,10000", 金币范围
--         -- ["leave_rate"] = 80,    离桌率(百分比)
--         if not self.robot_data then
--             errlog('load_robot fail because robotdata is nil')
--             return
--         end
--         --当前人数超过桌子总人数 把号放回robog_mgr节点
--         if self.user_manager:getLeftUserNum() <= 0 then
--             self:reset()
--             return
--         end
        
--         local robot_num_map = {} --当前机器人各个类型的人数
--         local user_list = self.user_manager:getUserList()
--         for uid, user in pairs(user_list) do        
--             if user:isRobot() then
--                 local robot_type_id = user:getRobotTypeId()
--                 robot_num_map[robot_type_id] = (robot_num_map[robot_type_id] or 0) + 1
--             end
--         end

--         local load_list = {} --期望加载的个数

--         local robot_num = string_split(self.robot_data.count_range, ',')
--         local coins_limit = string_split(self.robot_data.coins_range, ',')
--         local robot_min = tonumber(robot_num[1]) or 0
--         local robot_max = tonumber(robot_num[2]) or 0
--         local count = math_random(robot_min, robot_max)
--         local curr_count = robot_num_map[id] or 0
--         if count > curr_count then
--             load_list[id] = {
--                 count = count - curr_count,
--                 coins_limit = {tonumber(coins_limit[1] or 0), tonumber(coins_limit[2]) or 0},
--             }                            
--         end

--         if not next(load_list) then 
--            errlog("红包扫雷 RobotManager加载机器人数为0")
--            self:reset()
--            return
--         end
--         --向robot_mgr节点请求机器人列表
--         local ok, succ, ret_map = R().robotmgr(1):call(".msg_handler", "get_robot_type_list", load_list, robot_type)
--         if not ok or not succ or not ret_map then
--             errlog("load rebot is fail because succ is nil")
--             return
--         end
--         --当前人数超过桌子总人数 把号放回robog_mgr节点
--         if self.user_manager:getLeftUserNum() <= 0 then
--             R().robotmgr(1):send('.msg_handler', 'put_back_robots', ret_map)
--             return
--         end
--         -- dbglog("__加载机器人______ret_map___________",dump(ret_map))
--         local curr_time = os.time()    
--         for _, robot_info in pairs(ret_map) do
--             local uid = robot_info.uid
--             local base_data = {
--                 uid = uid,
--                 coins = robot_info.coins,           
--                 vip_level = robot_info.vip_level or 0,          
--             }
--             local enter_data = {
--                 name = robot_info.name,
--                 icon = robot_info.icon,
--                 sex = robot_info.sex,
--                 icon_border = robot_info.icon_border,
--             }
--             local ok, err_code = self.user_manager:addRobot(base_data, enter_data)
--             local user = self.user_manager:getUser(uid)
--             user:setIsRobot(true) --是机器人
--             user:setRobotTypeId(robot_info.coins_type) --类型id
--             user:setFD(self.robot_client_fd)
--             user:setDisconnect(false) --断线标识
--             local robot = self:getRobot() --从池中取一个机器人
--             if robot then 
--                 robot:init(uid)        
--             end
--             self.robot_list[uid] = robot
--         end   
--         self.desk:ntMatchsvrTableStats() --回传状态给newmatchsvr

--         self:reset()
--         dbglog("红包扫雷__加载机器人______结束_________")
--     end
-- end

--创建相关对象
local function init()
    local hotfix = Hotfix.new()
    hotfix:start()
    global.hotfix = hotfix

    local message_dispatch = MessageDispatch.new()  
    local desk = Desk.new()
    local desk_message = DeskMessage.new(message_dispatch)
    local message_handler = MessageHandler.new(message_dispatch)
    local room_config = RoomConfig.new()
    local user_manager = UserManager.new(room_config)
    local robot_manager = RobotManager.new(message_dispatch)
    local store_manager = StoreManager.new(message_dispatch)
    -- resetFu(robot_manager)
    global.game_name = game_name
    global.message_dispatch = message_dispatch  
    global.desk = desk
    global.user_manager = user_manager
    global.desk_message = desk_message
    global.room_config = room_config
    global.message_handler = message_handler
    global.robot_manager = robot_manager
    global.store_manager = store_manager

    
    --
    skynet.register_protocol({
        name = "client",
        id = skynet.PTYPE_CLIENT,
        pack = skynet.pack,
        unpack = skynet.unpack,
    })
    
    --消息派发
    local func = message_dispatch:dispatchClient()  
    skynet.dispatch("client", func)
    skynet.dispatch("lua", message_dispatch:dispatchLua())
    dbglog("_______红包扫雷游戏服启动________________")
end

---------------------------------------------------------
-- skynet service start
---------------------------------------------------------
disable_global()
init()
skynet.start(function() end)